package com.jiangchao.mimidao.framework.factory;

import java.lang.annotation.Annotation;
import java.util.Set;
import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition;
import org.springframework.beans.factory.config.BeanDefinitionHolder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.GenericBeanDefinition;
import org.springframework.context.annotation.ClassPathBeanDefinitionScanner;
import org.springframework.core.type.filter.AnnotationTypeFilter;

public class MimiDaoScanner extends ClassPathBeanDefinitionScanner {

  public MimiDaoScanner(
      BeanDefinitionRegistry registry, Class<? extends Annotation> annotation) {
    super(registry, false);
    addIncludeFilter(new AnnotationTypeFilter(annotation));
  }

  @Override
  protected Set<BeanDefinitionHolder> doScan(String... basePackages) {
    Set<BeanDefinitionHolder> beanDefinitionHolders = super.doScan(basePackages);
    GenericBeanDefinition definition;
    for (BeanDefinitionHolder holder : beanDefinitionHolders) {
      definition = (GenericBeanDefinition) holder.getBeanDefinition();
      definition.getPropertyValues()
          .add("proxy", getRegistry().getBeanDefinition("mimiDaoHandler"));
      definition.getPropertyValues().add("daoInterface", definition.getBeanClassName());
      if (logger.isInfoEnabled()) {
        logger.info("register mimidao name is { " + definition.getBeanClassName() + " }");
      }
      definition.setBeanClass(MimiDaoBeanFactory.class);
    }

    return beanDefinitionHolders;
  }

  @Override
  protected boolean isCandidateComponent(AnnotatedBeanDefinition beanDefinition) {
    return beanDefinition.getMetadata().isInterface() && beanDefinition.getMetadata()
        .isIndependent();
  }
}
